﻿using LIT.Logger.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace LIT.Logger.ServerCheckerBL.Checkers
{
    public class ServiceAndProcess
    {
        private IEventSender m_eventSender;
        private IConfiguration m_config;

        public ServiceAndProcess(IEventSender _eventSender, IConfiguration _config)
        {
            if (_eventSender == null)
                throw new ArgumentNullException("_eventSender");
            if (_config == null)
                throw new ArgumentNullException("_config");
            this.m_eventSender = _eventSender;
            this.m_config = _config;
        }

        public void CheckServices()
        {
            foreach (string service in m_config.CheckServices)
            {
                try
                {
                    ServiceController sc = new ServiceController(service);
                    if (sc.Status != ServiceControllerStatus.Running)
                    {
                        m_eventSender.ReportEvent(new Event("Service is not running.", EventType.ERROR)
                        {
                            Details = string.Format("Service name: {0}", service)
                        });
                    }
                    m_eventSender.ReportEvent(new Event("Service checked", EventType.DEBUG, service));
                }
                catch (Exception ex)
                {
                    m_eventSender.ReportException(new ExceptionEvent("Service status could not be read.",
                        EventType.ERROR, ex)
                        {
                            Details = string.Format("Service name: {0}", service)
                        });
                }
            }
        }

        public void CheckProcesses()
        {
            foreach (string process in m_config.CheckProcesses)
            {
                try
                {
                    if (System.Diagnostics.Process.GetProcessesByName(process).Count() == 0)
                        m_eventSender.ReportEvent(new Event("Process is not running.", EventType.ERROR)
                        {
                            Details = string.Format("Process name: {0}", process)
                        });
                    m_eventSender.ReportEvent(new Event("Process checked", EventType.DEBUG, process));
                }
                catch (Exception ex)
                {
                    m_eventSender.ReportException(new ExceptionEvent("Error reading process information.", EventType.ERROR, ex)
                    {
                        Details = string.Format("Process name: {0}", process)
                    });
                }
            }
        }
    }
}